<?php


namespace app\api\service;

use app\api\model\Member;
use think\Cache;
use think\Config;

class Login{

    protected $appid;
    protected $secret;
    protected $loginUrl;

    public function __construct(){
        $this->appid = Config('wxinfo.appId');
        $this->secret = Config('wxinfo.secretId');
        $this->loginUrl = Config('wxinfo.loginUrl');
    }

    //使用openid作为用户唯一标示符进行数据交互
    public function getOpenid($code){
        $url = sprintf($this->loginUrl,$this->appid,$this->secret,$code);
        $result = https_request($url);
        $wxResult = json_decode($result,true);
        if(empty($wxResult)){
        	return error('获取sessin_key及openID时异常');
        }
        if(isset($wxResult['errcode']) && $wxResult['errcode'] !=0){
        	return error($wxResult['errmsg'],$wxResult['errcode']);
        }

        $member = new Member();
        $item = $member->getMember($wxResult['openid']);
        if(empty($item)){
            $member->openid = $wxResult['openid'];
            $member->createtime = time();
            $member->save();
        }
        return success($wxResult);
    }

    //使用token作为用户唯一标示符进行数据交互
    public function getOpenids($code){
        $url = sprintf($this->loginUrl,$this->appid,$this->secret,$code);
        $result = https_request($url);
        $wxResult = json_decode($result,true);

	    if(empty($wxResult)){
		    return error('获取sessin_key及openID时异常');
	    }
	    if(isset($wxResult['errcode']) && $wxResult['errcode'] !=0){
		    return error($wxResult['errmsg'],$wxResult['errcode']);
	    }

        $member = new Member();
        $item = $member->getMember($wxResult['openid']);
        if(empty($item)){
            $member->openid = $wxResult['openid'];
            $member->createtime = time();
            $member->save();
            $token = ['id'=>$member->id,'openid'=>$member->openid];
        }

        $token = ['id'=>$item->id,'openid'=>$item->openid];

        $accessTokenModel = new Accesstoken();
        $token = $accessTokenModel::setTokenByOpenid($token);
        $item = [
            'token' => $token,
            'session_key' =>$wxResult['session_key']
        ];
        return success($item);
    }
}